package com.yunnuo.system.controller;

import com.yunnuo.common.utils.ShiroUtils;
import com.yunnuo.common.utils.StringUtils;
import com.yunnuo.common.web.ResultData;
import net.sf.json.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * @api {title} 系统登陆comtroller
 * @apiName LoginController
 * @apiGroup System-logincontroller
 * @apiDescription Created by 魏洪福(15064000912@163.com) on  2018/5/25.
 */
@Controller
public class LoginController {

    /**
     * @api {get} / 系统默认跳转地址
     * @apiName welcome
     * @apiGroup System-logincontroller
     */
    @GetMapping({ "/", "" })
    String welcome(Model model) {
        return "redirect:/login";
    }

    /**
     * @api {get} /login  跳转系统登陆
     * @apiName login
     * @apiGroup System-logincontroller
     */
    @GetMapping("/login")
    String login() {
        return "login";
    }

    /**
     * @api {post} /login  系统登陆
     * @apiName login
     * @apiGroup System-logincontroller
     */
    @PostMapping("/login")
    @ResponseBody
    public JSON ajaxLogin(String username, String password)
    {
        ResultData data = new ResultData();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            data.setData("");
            data.setStat(ResultData.STAT_SUCCESS);
            data.setMessage("操作成功！");
            return data.toJson();
        }
        catch (AuthenticationException e)
        {
            data.setStat(ResultData.STAT_FAILURE);
            data.setData("");
            data.setMessage("用户名或密码错误");
            return data.toJson();
        }
    }
    /**
     * @api {get} /logout  退出登录
     * @apiName logout
     * @apiGroup System-logincontroller
     */
    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }



}
